# coding=utf-8
# -*- coding: UTF-8 -*-
#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import logging
from typing import Any
from urllib import parse

from flask_sqlalchemy import SQLAlchemy

from ksai.context import ApplicationInitializer, Application
from ksai.persistence.database.config import driver_mapping, database_config
from ksai.utils.strings import has_text

db = SQLAlchemy()

logger = logging.getLogger(__name__)


def resolve_database_url():
    driver = driver_mapping[database_config.DATABASE_TYPE]
    parsed_username = parse.quote_plus(database_config.DATABASE_USERNAME)
    parsed_password = parse.quote_plus(database_config.DATABASE_PASSWORD)
    parsed_host = parse.quote_plus(database_config.DATABASE_HOST)
    url = f"{driver}://{parsed_username}:{parsed_password}@{parsed_host}"

    if has_text(str(database_config.DATABASE_PORT)):
        url = f"{url}:{str(database_config.DATABASE_PORT)}"
    url = f"{url}/"

    if has_text(database_config.DATABASE_NAME):
        parsed_database = parse.quote_plus(database_config.DATABASE_NAME)
        url = f"{url}{parsed_database}"

    if has_text(database_config.DATABASE_PROPERTIES):
        url = f"{url}?{database_config.DATABASE_PROPERTIES}"
    logging.debug(f"Database URL: {url}")

    return url


class DatabasePersistenceInitializer(ApplicationInitializer):

    def initialize(self, app: Application) -> Any:
        database_url = resolve_database_url()
        app.config['SQLALCHEMY_DATABASE_URI'] = database_url
        app.config["SQLALCHEMY_ECHO"] = app.config['DEBUG'] is True
        db.init_app(app)


class DatabaseMigrateInitializer(ApplicationInitializer):

    def initialize(self, app: Application) -> Any:
        from flask_migrate import Migrate
        migrate = Migrate(app, db, version_table=database_config.DATABASE_CHANGELOG_TABLE)
        migrate.init_app(app, db)
